package com.demo.practiceui.views.animation;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

/**
 * 渐变圆环加载动画
 * 核心知识点：
 * 1. SweepGradient - 扫描渐变
 * 2. canvas.rotate() - 旋转画布
 * 3. drawArc - 绘制圆弧
 * 4. 组合动画 - 旋转 + 透明度
 */
public class LoadingRingView extends View {

    // 画笔
    private Paint ringPaint;
    private Paint bgPaint;

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;
    private float radius;
    private float strokeWidth = 20f;

    private RectF rectF;

    // 动画参数
    private float rotation = 0f;        // 旋转角度
    private float sweepAngle = 270f;    // 圆弧角度

    // 动画
    private ValueAnimator rotationAnimator;

    // 渐变颜色
    private int[] gradientColors = {
            Color.parseColor("#4CAF50"),
            Color.parseColor("#2196F3"),
            Color.parseColor("#9C27B0"),
            Color.parseColor("#FF5722")
    };

    public LoadingRingView(Context context) {
        this(context, null);
    }

    public LoadingRingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingRingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 背景圆环画笔
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setColor(Color.parseColor("#E0E0E0"));
        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setStrokeWidth(strokeWidth);
        bgPaint.setStrokeCap(Paint.Cap.ROUND);

        // 渐变圆环画笔
        ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        ringPaint.setStyle(Paint.Style.STROKE);
        ringPaint.setStrokeWidth(strokeWidth);
        ringPaint.setStrokeCap(Paint.Cap.ROUND);

        rectF = new RectF();

        startAnimation();
    }

    /**
     * 启动动画
     */
    private void startAnimation() {
        // 旋转动画
        rotationAnimator = ValueAnimator.ofFloat(0, 360);
        rotationAnimator.setDuration(1500);
        rotationAnimator.setRepeatCount(ValueAnimator.INFINITE);
        rotationAnimator.setInterpolator(new LinearInterpolator());
        rotationAnimator.addUpdateListener(animation -> {
            rotation = (float) animation.getAnimatedValue();
            invalidate();
        });
        rotationAnimator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 300;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 300;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f;
        radius = Math.min(width, height) / 2f - strokeWidth - 20;

        rectF.set(centerX - radius, centerY - radius,
                centerX + radius, centerY + radius);

        // 设置扫描渐变
        SweepGradient gradient = new SweepGradient(centerX, centerY, gradientColors, null);
        ringPaint.setShader(gradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景圆环
        canvas.drawCircle(centerX, centerY, radius, bgPaint);

        // 2. 保存画布状态
        canvas.save();

        // 3. 旋转画布
        canvas.rotate(rotation, centerX, centerY);

        // 4. 绘制渐变圆弧
        canvas.drawArc(rectF, 0, sweepAngle, false, ringPaint);

        // 5. 恢复画布状态
        canvas.restore();

        // 6. 绘制中心文字
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#666666"));
        textPaint.setTextSize(36f);
        textPaint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("加载中...", centerX, centerY + 12, textPaint);
    }

    /**
     * 设置加载状态
     */
    public void setLoading(boolean loading) {
        if (loading) {
            if (!rotationAnimator.isRunning()) {
                rotationAnimator.start();
            }
        } else {
            if (rotationAnimator.isRunning()) {
                rotationAnimator.cancel();
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (rotationAnimator != null) {
            rotationAnimator.cancel();
        }
    }
}

